<template>
  <div class="point-stru-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <ButtonGroup>
            <el-button
              type="primary"
              icon="Plus"
              @click="handleAdd(null)"
            >新增</el-button>
          </ButtonGroup>
        </div>
      </template>
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="pointStruList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="量测模型名称" prop="pointModelCnName" show-overflow-tooltip />
        <el-table-column label="量测模型英文名称" prop="pointModelEnName" show-overflow-tooltip />
        <el-table-column label="起始地址" prop="pointModelStartAddr" width="120" align="center" />
        <el-table-column label="数量" prop="pointModelNumAddr" width="80" align="center" />
        <el-table-column label="信号类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag >
              {{ getSignalTypeLabel(row.pointSignalType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort" width="60" align="center" />
        <el-table-column label="网关ID" prop="gatewayId" width="100" align="center" />
<!--        -->
<!--        <el-table-column label="状态" align="center" width="80">-->
<!--          <template #default="{ row }">-->
<!--            <el-tag :type="row.status === 1 ? 'success' : 'info'">-->
<!--              {{ row.status === 1 ? '启用' : '禁用' }}-->
<!--            </el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
        
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button type="success" link @click="handleAdd(row)" >
              <el-icon><Plus /></el-icon>新增
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>修改
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改量测模型对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增量测模型' : '修改量测模型'"
      width="700px"
      append-to-body
    >
      <el-form
        ref="pointStruFormRef"
        :model="pointStruForm"
        :rules="rules"
        label-width="150px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="上级模型" prop="parentId">
              <el-tree-select
                v-model="pointStruForm.parentId"
                :data="pointStruOptions"
                :props="{ label: 'pointModelCnName', value: 'id' }"
                value-key="id"
                placeholder="选择上级模型"
                check-strictly
                :render-after-expand="false"
                class="flex-grow"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="量测模型中文名称" prop="pointModelCnName">
              <el-input v-model="pointStruForm.pointModelCnName" placeholder="请输入量测模型中文名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="量测模型英文名称" prop="pointModelEnName">
              <el-input v-model="pointStruForm.pointModelEnName" placeholder="请输入量测模型英文名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="量测点位起始地址" prop="pointModelStartAddr">
              <el-input-number v-model="pointStruForm.pointModelStartAddr" :min="0" class="flex-grow" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="量测数量" prop="pointModelNumAddr">
              <el-input-number v-model="pointStruForm.pointModelNumAddr" :min="1" class="flex-grow" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="信号类型" prop="pointSignalType">
              <el-select v-model="pointStruForm.pointSignalType" placeholder="请选择信号类型" class="flex-grow" disabled>
                <el-option label="遥测" :value="0" />
                <el-option label="遥信" :value="1" />
                <el-option label="遥调" :value="2" />
                <el-option label="遥控" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="pointStruForm.sort" :min="1" class="flex-grow" />
            </el-form-item>
          </el-col>


        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import {
  getPointStruTreeApi,
  createPointStruApi,
  updatePointStruApi,
  deletePointStruApi,
} from '@/api/ems/pointStru/pointStru'
import { useRoute} from "vue-router";
const route = useRoute();
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const pointStruFormRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单校验规则
const rules = {
  parentId: [
    { required: true, message: '请选择上级模型', trigger: 'blur' }
  ],
  pointModelCnName: [
    { required: true, message: '请输入量测模型中文名称', trigger: 'blur' }
  ],
  pointModelEnName: [
    { required: true, message: '请输入量测模型英文名称', trigger: 'blur' }
  ],
  pointModelStartAddr: [
    { required: true, message: '请输入量测点位起始地址', trigger: 'blur' }
  ],
  pointModelNumAddr: [
    { required: true, message: '请输入量测数量', trigger: 'blur' }
  ],
  pointSignalType: [
    { required: true, message: '请选择信号类型', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ],
}
//网关ID（）
const gatewayId = ref();
const pointSignalType = ref()
const pointStruQueryForm = reactive<any>({

  pointSignalType: pointSignalType.value,
  gatewayId: gatewayId.value,
})
// 量测模型表单对象
const pointStruForm = reactive<any>({
  id: undefined,
  parentId: 0,
  pointModelCnName: '',
  pointModelEnName: '',
  pointModelStartAddr: 0,
  pointModelNumAddr: 1,
  pointSignalType: 1,
  sort: 1,
  gatewayId: gatewayId.value,
})

// 模拟量测模型数据
const pointStruList = ref<any>([])

// 量测模型树选项
const pointStruOptions = ref<any>([])

// 信号类型标签映射
const getSignalTypeTag = (type: number) => {
  const tagMap = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info'
  }
  return tagMap[type as keyof typeof tagMap] || 'info'
}

// 信号类型标签文字映射
const getSignalTypeLabel = (type: number) => {
  const labelMap = {
    0: '遥测',
    1: '遥信',
    2: '遥调',
    3: '遥控'
  }
  return labelMap[type as keyof typeof labelMap] || '未知'
}

// 查询方法
const getList = async () => {
  loading.value = true
  try {
    // 模拟数据 - 实际使用时请调用真实API
    const mockData = [
      {
        id: 1,
        pointModelCnName: '电压量测模型',
        pointModelEnName: 'VoltageMeasurement',
        pointModelStartAddr: 1000,
        pointModelNumAddr: 50,
        pointSignalType: 1,
        sort: 1,
        gatewayId: 101,
        status: 1,
        parentId: 0,
        children: [
          {
            id: 11,
            pointModelCnName: 'A相电压',
            pointModelEnName: 'PhaseAVoltage',
            pointModelStartAddr: 1001,
            pointModelNumAddr: 1,
            pointSignalType: 1,
            sort: 1,
            gatewayId: 101,
            status: 1,
            parentId: 1
          },
          {
            id: 12,
            pointModelCnName: 'B相电压',
            pointModelEnName: 'PhaseBVoltage',
            pointModelStartAddr: 1002,
            pointModelNumAddr: 1,
            pointSignalType: 1,
            sort: 2,
            gatewayId: 101,
            status: 1,
            parentId: 1
          },
          {
            id: 13,
            pointModelCnName: 'C相电压',
            pointModelEnName: 'PhaseCVoltage',
            pointModelStartAddr: 1003,
            pointModelNumAddr: 1,
            pointSignalType: 1,
            sort: 3,
            gatewayId: 101,
            status: 1,
            parentId: 1
          }
        ]
      },
      {
        id: 2,
        pointModelCnName: '电流量测模型',
        pointModelEnName: 'CurrentMeasurement',
        pointModelStartAddr: 2000,
        pointModelNumAddr: 30,
        pointSignalType: 1,
        sort: 2,
        gatewayId: 101,
        status: 1,
        parentId: 0,
        children: [
          {
            id: 21,
            pointModelCnName: 'A相电流',
            pointModelEnName: 'PhaseACurrent',
            pointModelStartAddr: 2001,
            pointModelNumAddr: 1,
            pointSignalType: 1,
            sort: 1,
            gatewayId: 101,
            status: 1,
            parentId: 2
          },
          {
            id: 22,
            pointModelCnName: 'B相电流',
            pointModelEnName: 'PhaseBCurrent',
            pointModelStartAddr: 2002,
            pointModelNumAddr: 1,
            pointSignalType: 1,
            sort: 2,
            gatewayId: 101,
            status: 1,
            parentId: 2
          }
        ]
      },
      {
        id: 3,
        pointModelCnName: '开关状态模型',
        pointModelEnName: 'SwitchStatusModel',
        pointModelStartAddr: 3000,
        pointModelNumAddr: 20,
        pointSignalType: 2,
        sort: 3,
        gatewayId: 101,
        status: 1,
        parentId: 0
      },
      {
        id: 4,
        pointModelCnName: '温度量测模型',
        pointModelEnName: 'TemperatureMeasurement',
        pointModelStartAddr: 4000,
        pointModelNumAddr: 15,
        pointSignalType: 1,
        sort: 4,
        gatewayId: 101,
        status: 0,
        parentId: 0
      }
    ]
    getPointStruTreeApi(pointStruQueryForm).then(res => {
      pointStruList.value = res.data
      const topPointStru = {id: 0, pointModelCnName: '顶级模型', children: pointStruList.value}
      console.log(pointStruList.value,topPointStru,"topPointStru")
      pointStruOptions.value = [topPointStru]
    })


  } catch (error) {
    console.error('获取量测模型列表失败:', error)
  }
  loading.value = false
}

// 提交表单
const submitForm = async () => {
  if (!pointStruFormRef.value) return
  
  await pointStruFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const formData = { ...pointStruForm }
        
        if (dialogType.value === 'add') {
          await createPointStruApi(formData)
          ElMessage.success('新增成功')
        } else {
          await updatePointStruApi(formData)
          ElMessage.success('修改成功')
        }
        
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交表单失败:', error)
      }
      submitLoading.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  pointStruForm.id = undefined
  pointStruForm.parentId = 0
  pointStruForm.pointModelCnName = ''
  pointStruForm.pointModelEnName = ''
  pointStruForm.pointModelStartAddr = 0
  pointStruForm.pointModelNumAddr = 1
  pointStruForm.sort = 1
  pointStruForm.gatewayId = Number(gatewayId.value);
  pointStruForm.pointSignalType = Number(pointSignalType.value);
}

// 新增按钮操作
const handleAdd = (row?: any) => {
  resetForm()
  dialogType.value = 'add'
  
  if (row) {
    pointStruForm.parentId = row.id
  }
  
  dialogVisible.value = true
}

// 修改按钮操作
const handleEdit = (row: any) => {
  resetForm()
  dialogType.value = 'edit'
  
  // 填充表单数据
  Object.assign(pointStruForm, row)
  
  dialogVisible.value = true
}

// 删除按钮操作
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定删除量测模型"${row.pointModelCnName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deletePointStruApi(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    // 用户取消删除
  }
}

// 初始化
onMounted(() => {
  pointSignalType.value = Number(route.query.pointSignalType);
  gatewayId.value = Number(route.query.gatewayId);
  pointStruQueryForm.gatewayId = Number(gatewayId.value) ;
  pointStruQueryForm.pointSignalType = Number(pointSignalType.value);
  pointStruForm.gatewayId = Number(gatewayId.value);
  pointStruForm.pointSignalType = Number(pointSignalType.value);

  getList()
})
</script>

<style lang="scss" scoped>
.point-stru-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flex-grow {
  width: 100%;
}

.status-group {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>